package com.cangxuan.app.ui.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.util.DisplayMetrics;
import android.view.*;
import android.widget.*;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.Goods;
import com.cangxuan.app.entity.Order;
import com.cangxuan.app.entity.Registration;
import com.cangxuan.app.entity.User;
import com.cangxuan.app.ui.collection.CollectionDetailActivity;
import com.cangxuan.app.ui.collection.OrderPayActivity;
import com.cangxuan.app.ui.user.AccountSecurityActivity;
import com.cangxuan.app.ui.user.MyCollectionActivity;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.UserUtils;

import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.*;


/**
 * Author: 陈青石
 * Activity: 藏品详情 片段
 * Layout: fragment_collectiondetail_bottom
 */
public class CollectionDetailBottomFragment extends Fragment {


    public static class MyCountDialog extends Dialog {
        Context context;

        private ClickListenerInterface clickListenerInterface;

        interface ClickListenerInterface {
            void cancelListener();

            void sureListener(EditText view);
        }

        public void setClickListener(ClickListenerInterface clickListenerInterface) {
            this.clickListenerInterface = clickListenerInterface;
        }


        public MyCountDialog(Context context, int style) {
            super(context, style);
            this.context = context;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            init();
        }

        public void init() {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            View view = layoutInflater.inflate(R.layout.activity_account_security_nickname, null);
            setContentView(view);
            Button cancel = view.findViewById(R.id.nickname_cancel);
            Button sure = view.findViewById(R.id.nickname_sure);
            TextView title = view.findViewById(R.id.dialog_title);
            EditText edit = view.findViewById(R.id.dialog_edit);
            title.setText("购买数量");
            edit.setHint("输入购买数量");
            edit.setText(String.valueOf(1));
            Window dialogWindow = getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();

            DisplayMetrics d = context.getResources().getDisplayMetrics();
            lp.width = (int) (d.widthPixels * 0.8);

            dialogWindow.setAttributes(lp);
            cancel.setOnClickListener(new ClickListener());
            sure.setOnClickListener(new ClickListener(edit));
        }


        public class ClickListener implements View.OnClickListener {

            EditText view;

            public ClickListener() {
            }

            public ClickListener(EditText view) {
                this.view = view;
            }

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.nickname_cancel:
                        clickListenerInterface.cancelListener();
                        break;
                    case R.id.nickname_sure:

                        clickListenerInterface.sureListener(view);
                        break;
                }
            }
        }


    }


    static class ListsAdapter extends BaseAdapter {

        private List<Registration> listTestEntities;
        ;

        public ListsAdapter(List<Registration> listTestEntities) {
            this.listTestEntities = listTestEntities;
        }

        @Override
        public int getCount() {
            return listTestEntities.size();
        }

        @Override
        public Object getItem(int i) {
            return listTestEntities.get(i);
        }

        @Override
        public long getItemId(int i) {
            return listTestEntities.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            //声明视图持有类实例
            ListsViewHolder viewHolder;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(R.layout.activity_collectiondetali_list_item, viewGroup, false);
                viewHolder = new ListsViewHolder();
                //给viewHolder中的属性（控件）进行初始化
                viewHolder.listName = view.findViewById(R.id.list_name);
                viewHolder.listCode = view.findViewById(R.id.list_code);
                viewHolder.listPrice = view.findViewById(R.id.list_price);
                viewHolder.listCheckBox = view.findViewById(R.id.list_checkbox);
                viewHolder.listBuy = view.findViewById(R.id.list_buy);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ListsViewHolder) view.getTag();
            }
            Registration listTestEntity = listTestEntities.get(i);

            viewHolder.listName.setText("收藏家" + listTestEntity.getUserId());
            viewHolder.listCode.setText("编号:NO." + listTestEntity.getId());
            viewHolder.listPrice.setText("￥" + listTestEntity.getPrice());
            viewHolder.listCheckBox.setChecked(listTestEntity.isChecked());
            viewHolder.listCheckBox.setEnabled(listTestEntity.isClicked());

            viewHolder.listCheckBox.setOnClickListener(view1 -> {

                if (CollectionDetailActivity.registrations.get(i).isChecked()) {
                    checkCount -= 1;
                } else {
                    checkCount += 1;
                }

                CollectionDetailActivity.registrations.get(i).setChecked(!listTestEntity.isChecked());
                setCountAndPrice(CollectionDetailActivity.registrations);
                CollectionDetailListBottomFragment.setListCountAndPrice(CollectionDetailActivity.registrations);
                setMaxCheck();
            });

            viewHolder.listBuy.setOnClickListener(view1 -> {
                Registration registration = CollectionDetailActivity.registrations.get(i);
                if (registration.isClicked()) {
                    createSingleOrder(registration);
                }
            });
            return view;
        }

        /**
         * 视图持有类，
         * 该类的属性会包含ListView的项里面需要动态设置值的控件
         */
        class ListsViewHolder {
            TextView listName;
            TextView listCode;
            TextView listPrice;
            CheckBox listCheckBox;
            Button listBuy;
        }

    }

    private static void createSingleOrder(Registration registration) {
        if (UserUtils.getUser(context) == null) {
            Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        if (UserUtils.getUser(context).isHasSetRealname() == false) {
            Toast.makeText(context, "请先实名认证", Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog = ProgressDialog.show(context, "", "创建订单中请稍等...");

        List<Registration> sendRegistration = new ArrayList<>();
        sendRegistration.add(registration);
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(sendRegistration));
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.post("/api/registration/updateBuyerId", header, String.valueOf(array));
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONObject responseJSONObject = jsonResponse.getJSONObject("value");
                handler.post(() -> {
                    CollectionDetailListBottomFragment.isOpen = 1;
                    dialog.dismiss();
                    progressDialog.dismiss();

                    Intent intent = new Intent(context, OrderPayActivity.class);
                    intent.putExtra("orderform", (Serializable) responseJSONObject.get("list"));
                    intent.putExtra("sum", responseJSONObject.get("sum").toString());
                    intent.putExtra("topIndex", 1);
                    intent.putExtra("comeFrom", 1);
                    context.startActivity(intent);
                });
            } else {
                handler.post(() -> {
                    checkCount = 0;
                    successDoChangeList();
                    Toast.makeText(context, jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }

    private static void successDoChangeList() {
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/registration/get/" + CollectionDetailActivity.id, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonArray = jsonResponse.getJSONArray("value");
                CollectionDetailActivity.registrations = JSONObject.parseArray(jsonArray.toJSONString(), Registration.class);
                handler.post(() -> {
                    CollectionDetailBottomFragment.changeList();
                    CollectionDetailBottomFragment.setCountAndPrice(CollectionDetailActivity.registrations);
                    CollectionDetailListBottomFragment.setListCountAndPrice(CollectionDetailActivity.registrations);
                    setMaxCheck();
                    progressDialog.dismiss();
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(context, jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }

    public static int checkCount = 0;

    public static void setMaxCheck() {
        User user = UserUtils.getUser(context);
        if (user==null){
            user=new User();
            user.setId(0);
        }

        if (checkCount == 10) {
            for (int i = 0; i < CollectionDetailActivity.registrations.size(); i++) {

                if (CollectionDetailActivity.registrations.get(i).getBuyerId() != 0) {
                    CollectionDetailActivity.registrations.get(i).setClicked(false);
                } else if (CollectionDetailActivity.registrations.get(i).getUserId() == user.getId()) {
                    CollectionDetailActivity.registrations.get(i).setClicked(false);
                } else {
                    if (CollectionDetailActivity.registrations.get(i).isChecked()) {
                        CollectionDetailActivity.registrations.get(i).setClicked(true);
                    } else {
                        CollectionDetailActivity.registrations.get(i).setClicked(false);
                    }
                }
            }
        } else {
            for (int i = 0; i < CollectionDetailActivity.registrations.size(); i++) {
                System.out.println(CollectionDetailActivity.registrations.get(i));
                if (CollectionDetailActivity.registrations.get(i).getBuyerId() == 0) {
                    if (CollectionDetailActivity.registrations.get(i).getUserId() == user.getId()) {
                        CollectionDetailActivity.registrations.get(i).setClicked(false);
                    } else {
                        CollectionDetailActivity.registrations.get(i).setClicked(true);
                    }
                } else {
                    CollectionDetailActivity.registrations.get(i).setClicked(false);
                }
            }

        }

        listsAdapter = new ListsAdapter(CollectionDetailActivity.registrations);
        listView.setAdapter(listsAdapter);
        listView.setOnScrollListener(listHistoryScroll);
        listView.setSelection(position);
    }

    private static AbsListView.OnScrollListener listHistoryScroll = new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                position = listView.getFirstVisiblePosition();
            }
        }

        @Override
        public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
        }
    };


    public static void setCountAndPrice(List<Registration> listTestEntities) {
        int count = 0;
        int sum = 0;
        for (Registration listTestEntity : listTestEntities) {
            if (listTestEntity.isChecked()) {
                count++;
                sum += listTestEntity.getPrice();
            }
        }
        goodsCount.setText("已选择" + count + "件藏品");
        goodsPrice.setText("共计:" + sum + "元");
    }


    Button submit;
    ConstraintLayout root;
    public static Dialog dialog;
    private View view;
    static TextView goodsCount;
    static TextView goodsPrice;
    static ListsAdapter listsAdapter;
    static ListView listView;
    static LinearLayout dialogMainPage;
    static LinearLayout dialogMarket;
    static TextView goodsOnePrice;
    public static int position = 0;

    int sort = 1;
    static Context context;
    static Handler handler = new Handler();
    static Map<String, String> header;
    static ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        context = getContext();

        if (view == null) {
            view = inflater.inflate(R.layout.fragment_collectiondetail_bottom, container, false);
        }
        if (dialog != null) {
            dialog.cancel();
            dialog = null;
        }
        header = new HashMap<>();
        header.put("Authorization", DeviceUtils.getDeviceID());

        dialogMainPage = view.findViewById(R.id.dialog_mainpage);
        dialogMarket = view.findViewById(R.id.dialog_market);
        goodsOnePrice = view.findViewById(R.id.goods_one_price);
        goodsCount = view.findViewById(R.id.goods_count);
        goodsPrice = view.findViewById(R.id.goods_price);


        submit = view.findViewById(R.id.submit);
        submit.setOnClickListener(view -> {
            //主页
            if (CollectionDetailActivity.comeFrom == 0) {
                showBuyCountDialog();
            }
            //市场
            else {
                showList();
            }
        });

        if (CollectionDetailActivity.comeFrom == 0) {
            dialogMainPage.setVisibility(View.VISIBLE);
            dialogMarket.setVisibility(View.GONE);
        } else {
            dialogMarket.setVisibility(View.VISIBLE);
            dialogMainPage.setVisibility(View.GONE);
        }

        return view;
    }

    public static void setFragmentVisible() {
        if (CollectionDetailActivity.comeFrom == 0) {
            dialogMarket.setVisibility(View.GONE);
            dialogMainPage.setVisibility(View.VISIBLE);
        } else {
            dialogMainPage.setVisibility(View.GONE);
            dialogMarket.setVisibility(View.VISIBLE);
        }

    }

    public static void setOnePrice(Goods goodsDetail) {
        goodsOnePrice.setText("单价:" + goodsDetail.getPrice());
    }

    private void showBuyCountDialog() {

        MyCountDialog myCountDialog = new MyCountDialog(getContext(), R.style.BottomDialog);
        myCountDialog.show();
        myCountDialog.setCanceledOnTouchOutside(false);
        myCountDialog.setClickListener(new MyCountDialog.ClickListenerInterface() {
            @Override
            public void cancelListener() {
                myCountDialog.dismiss();
            }

            @Override
            public void sureListener(EditText view) {
                if (UserUtils.getUser(getContext()) == null) {
                    Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (UserUtils.getUser(getContext()).isHasSetRealname() == false) {
                    Toast.makeText(context, "请先实名认证", Toast.LENGTH_SHORT).show();
                    return;
                }

                int count;
                try {
                    count = Integer.valueOf(view.getText().toString());
                } catch (Exception e) {
                    Toast.makeText(getContext(), "输入数据有误", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (count < 1) {
                    Toast.makeText(getContext(), "输入数据有误", Toast.LENGTH_SHORT).show();
                    return;
                }
                progressDialog = ProgressDialog.show(getContext(), "", "创建订单中请稍等...");

                Thread thread = new Thread(() -> {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("goodsId", CollectionDetailActivity.id);
                    jsonObject.put("count", count);
                    String jsonString = HttpUtils.post("/api/orderform/creatOrderForm", header, jsonObject.toJSONString());
                    JSONObject jsonResponse = JSONObject.parseObject(jsonString);
                    if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                        JSONObject responseJSONObject = jsonResponse.getJSONObject("value");
                        handler.post(() -> {
                            myCountDialog.dismiss();
                            progressDialog.dismiss();
                            Intent intent = new Intent(getContext(), OrderPayActivity.class);
                            intent.putExtra("orderform", JSONObject.toJSONString(responseJSONObject.get("orderform")));
                            intent.putExtra("topIndex", 0);
                            intent.putExtra("sum", responseJSONObject.get("sum").toString());
                            intent.putExtra("comeFrom", 0);
                            startActivity(intent);
                        });

                    } else {
                        handler.post(() -> {
                            myCountDialog.dismiss();
                            progressDialog.dismiss();
                            Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                        });
                    }
                });
                thread.start();

            }
        });

    }


    private void showList() {

        if (dialog == null) {
            dialog = new Dialog(getContext(), R.style.BottomDialog);
            root = (ConstraintLayout) LayoutInflater.from(getContext()).inflate(R.layout.activity_collectiondetali_list, null);
            ImageView back = root.findViewById(R.id.list_close);
            Button listSort = root.findViewById(R.id.list_sort);

            listView = root.findViewById(R.id.list_listview);

            listsAdapter = new ListsAdapter(CollectionDetailActivity.registrations);
            listView.setAdapter(listsAdapter);
            setListViewHeightBasedOnChildrenForPercent(listView, 0.8f);

            back.setOnClickListener(view -> {
                CollectionDetailListBottomFragment.isOpen = 0;
                dialog.dismiss();
            });
            listSort.setOnClickListener(view -> {
                sort = sort * -1;
                CollectionDetailActivity.registrations.sort((o1, o2) -> {
                    return -(o1.getPrice() - o2.getPrice()) * sort;
                });
                listsAdapter = new ListsAdapter(CollectionDetailActivity.registrations);
                listView.setAdapter(listsAdapter);
            });
            dialog.setCanceledOnTouchOutside(false);
            dialog.setContentView(root);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialogWindow.setWindowAnimations(R.style.dialogWindowAnim);

            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.x = 0;
            lp.y = 0;
            lp.width = (int) getResources().getDisplayMetrics().widthPixels;
            root.measure(0, 0);
            lp.height = root.getMeasuredHeight();
            lp.alpha = 9f;
            dialogWindow.setAttributes(lp);
        }
        dialog.show();
        setMaxCheck();
    }

    private void setListViewHeightBasedOnChildrenForPercent(ListView listView, float percent) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        int height = (int) ((totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))) * percent);
//        if (height < 1000) {
//            height = 1000;
//        }

        params.height = 1500;
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public static void changeList() {
        listsAdapter = new ListsAdapter(CollectionDetailActivity.registrations);
        listView.setAdapter(listsAdapter);
    }

}
